#include "myformdoc.h"

#include "qtoolbar.h"
#include <QVBoxLayout>

#include "qfontdialog.h"
#include "qfiledialog.h"
#include "qfileinfo.h"

MyFormDoc::MyFormDoc(QWidget *parent)
	: QWidget(parent)
	, ui(new Ui::MyFormDocClass())
{
	ui->setupUi(this);
	QToolBar* tool_bar = new QToolBar("文档", this);
	tool_bar->addAction(ui->action_Open);
	tool_bar->addAction(ui->action_Font);
	tool_bar->addSeparator();
	tool_bar->addAction(ui->action_Cut);
	tool_bar->addAction(ui->action_Copy);
	tool_bar->addAction(ui->action_Paste);
	tool_bar->addAction(ui->action_Redo);
	tool_bar->addAction(ui->action_Undo);
	tool_bar->addSeparator();
	tool_bar->addAction(ui->action_Close);

	tool_bar->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);

	QVBoxLayout* layout = new QVBoxLayout();
	layout->addWidget(tool_bar);
	layout->addWidget(ui->plainTextEdit);

	this->setLayout(layout);
}

MyFormDoc::~MyFormDoc()
{
	delete ui;
}

void MyFormDoc::on_action_Open_triggered()
{
	QString current_path = QCoreApplication::applicationDirPath();
	QString a_file_path = QFileDialog::getOpenFileName(this, "打开一个文件", current_path, 
		"C/C++文件(*.h *.hpp *.cpp *.c);;文本文件(*.txt);;所有文件(*.*)");
	if (a_file_path.isEmpty())
		return;

	QFile a_file(a_file_path);
	if (a_file.open(QIODevice::ReadOnly | QIODevice::Text))
	{
		ui->plainTextEdit->clear();
		QTextStream stream(&a_file);//文件流
		QString str;
		while (!stream.atEnd())
		{
			str = stream.readLine();
			ui->plainTextEdit->appendPlainText(str);
		}
		a_file.close();

		QFileInfo a_file_info(a_file_path);
		QString a_file_name = a_file_info.fileName();
		setWindowTitle(a_file_name);//用文件名当标题

		emit title_changed(a_file_name);
	}
}

void MyFormDoc::on_action_Font_triggered()
{
	QFont font = ui->plainTextEdit->font();//获取当前字体，以进一步修改

	bool result;
	font = QFontDialog::getFont(&result, font);

	if (result)
		ui->plainTextEdit->setFont(font);
}
